package com.hmall.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.IsearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchService implements IsearchService {

    //定义全局静态常量索引库名
    public static final String INDEX = "item";
    //注入RestHighLevelClient对象
    @Autowired(required = false)
    private RestHighLevelClient highLevelClient;

    //定义ObjectMapper用于json与java对象转换
    private ObjectMapper objectMapper = new ObjectMapper();

    //注入itemClient微服务对象
    @Autowired
    private ItemClient itemClient;


    /**
     * 搜索栏自动补全功能
     *
     * @param key
     * @return
     */
    @Override
    public List<String> suggestion(String key) {
        try {
            //1.构建查询对象
            SearchRequest searchRequest = new SearchRequest(INDEX);

            //2.构成自动补全查询对象
            searchRequest.source().suggest(new SuggestBuilder().addSuggestion("itemSuggestion",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key).skipDuplicates(true)
                            .size(13)));

            //3.执行查询
            SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //4.获取结果分组给List<String>并返回
            Suggest suggest = response.getSuggest();
            //5.得到推荐的对象
            CompletionSuggestion completionSuggestion = suggest.getSuggestion("itemSuggestion");
            //6.获取自动补全文档数据集合
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            //7.遍历集合
            List<String> resultList = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                resultList.add(text);
            }

            return resultList;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 过滤项聚合功能
     *
     * @param requestParams
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {


        try {
            //构建查询请求对象
            SearchRequest searchRequest = new SearchRequest(INDEX);
            //构建多条件查询
            searchRequest.source().query(getBoolQueryBuilder(requestParams));
            //设置size=0
            searchRequest.source().size(0);
            //设置聚合，聚合名和限制数量
            searchRequest.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(20));
            searchRequest.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));

            //执行查询请求
            SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //解析出分组后品种列表
            List<String> cityList = getKeyListByAggName(response, "categoryAgg");


            //解析出分组后品牌列表
            List<String> brandList = getKeyListByAggName(response, "brandAgg");

            //将三个列表分组到Map集合中返回
            Map<String, List<String>> map = new HashMap<>();
            map.put("brand", brandList);
            map.put("category", cityList);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //获取指定聚合名字的分组数据
    private List<String> getKeyListByAggName(SearchResponse response, String aggName) {
        //聚合对象
        Aggregations aggregations = response.getAggregations();
        //获取指定的集合结果对象
        Terms terms = aggregations.get(aggName);

        //匹配的聚合结果集合
        List<? extends Terms.Bucket> buckets = terms.getBuckets();

        //遍历
        List<String> nameList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            //分组的名字
            String groupName = bucket.getKeyAsString();
            //添加到集合中
            nameList.add(groupName);
        }

        return nameList;
    }

    //抽取出公用的多条件筛选
    private BoolQueryBuilder getBoolQueryBuilder(RequestParams requestParams) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //3.判断查询条件key是否为空, 字符串非空判断StringUtils.isNotEmpty(字符串)
        if (StringUtils.isNotEmpty(requestParams.getKey())) {
            //3.1 不为空全文检索"all"
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", requestParams.getKey()));
        } else {
            //3.2 为空全文检索所有
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //判断查询条件参数category是否有效
        if (StringUtils.isNotEmpty(requestParams.getCategory())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", requestParams.getCategory()));
        }
        //判断查询条件参数brand是否有效
        if (StringUtils.isNotEmpty(requestParams.getBrand())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", requestParams.getBrand()));
        }

        //判断查询条件参数maxPrice和minPrice是否有效
        if (requestParams.getMaxPrice() != null && requestParams.getMinPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price")
                    .gte(requestParams.getMinPrice())
                    .lte(requestParams.getMaxPrice()));
        }
        return boolQueryBuilder;
    }

    /**
     * 商品条件查询
     *
     * @param requestParams
     * @return
     */

    //商品广告排名
    @Override
    public PageDTO<ItemDoc> itemList(RequestParams requestParams) {
        //- 关键字搜索
        // - 分类、品牌、价格过滤
        // - 排序
        // - 分页
        // - 高亮
        // - 竞价排名

        try {
            //1.判断查询页码 和 每页大小是否为null, 如果为null，设置默认值 page=1 和 size=5
            if (requestParams.getPage() == null) {
                requestParams.setPage(1);
            }
            if (requestParams.getSize() == null) {
                requestParams.setSize(5);
            }

            //2.创建搜索请求对象 SearchRequest
            SearchRequest searchRequest = new SearchRequest(INDEX);

            //创建BoolQueryBuilder来封装多个查询条件
            BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(requestParams);

            //增加算法函数，重新算分
            FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                    boolQueryBuilder,
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                    QueryBuilders.termQuery("isAD", "true"),
                                    ScoreFunctionBuilders.weightFactorFunction(10)
                            )
                    }
            ).boostMode(CombineFunction.SUM);

            //设置算分查询
            searchRequest.source().query(functionScoreQueryBuilder);
            //4.计算分页起始位置，公式=（当前页-1）* 每页大小
            Integer from = (requestParams.getPage() - 1) * requestParams.getSize();
            //5.设置查询分页from和size
            searchRequest.source().from(from).size(requestParams.getSize());

            //6.设置高亮查询字段，使用HighlightBuilder对象构建高亮字段
            searchRequest.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

            //销量排序(普通字段排序)
            if (StringUtils.isNotEmpty(requestParams.getSortBy()) && "sold".equals(requestParams.getSortBy())) {
                searchRequest.source().sort(SortBuilders.fieldSort("sold").order(SortOrder.DESC));
            }

            //价格排序
            if (StringUtils.isNotEmpty(requestParams.getSortBy()) && "price".equals(requestParams.getSortBy())) {
                searchRequest.source().sort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
            }

            //7.执行搜索，获取结果
            SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //8.封装结果并返回
            SearchHits searchHits = response.getHits();
            //9.获取总记录数
            long count = searchHits.getTotalHits().value;
            //10.遍历获取文档集合数据
            //定义集合List<HotelDoc>收集数据
            ArrayList<ItemDoc> itemDocList = new ArrayList<>();
            for (SearchHit searchHit : searchHits) {

                //10.1 获取每个文档的json数据
                String json = searchHit.getSourceAsString();

                //10.2 json转换为HotelDoc对象
                ItemDoc itemDoc = objectMapper.readValue(json, ItemDoc.class);

                //10.3替换高亮内容
                HighlightField nameHighlightField = searchHit.getHighlightFields().get("name");
                if (nameHighlightField != null) {
                    itemDoc.setName(nameHighlightField.getFragments()[0].toString());
                }

                //10.4 将hotelDoc对象添加到集合中
                itemDocList.add(itemDoc);
            }
            //11.封装分页数据返回
            return new PageDTO(count, itemDocList);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }


    //TODO

    /**
     * 新增，更新商品到es索引库
     *
     * @param id
     */
    @Override
    public void addItem(Long id) {
        //ea业务层根据商品id在mysql查找商品信息，更新到es索引库
        try {
            //1.获取数据库数据 Item对象
            Item item = itemClient.findById(id);

            //2.将Item封装到ItemHoc
            ItemDoc itemDoc = new ItemDoc(item);

            //3.创建 IndexRequest 请求对象，并构建 DSL 添加后修改文档命令
            //3.1 构建添加文档命令，格式为：POST item/_doc/id
            IndexRequest indexRequest = new IndexRequest(INDEX).id(itemDoc.getId().toString());

            //3.2 将itemDoc对象转换为json字符串
            String json = objectMapper.writeValueAsString(itemDoc);

            //3.3 继续构建添加文档命令填充文档数据，格式为：POST item/_doc/id{文档数据}
            indexRequest.source(json, XContentType.JSON);

            //4.执行添加文档命令并获取返回结果对象
            highLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除商品在es索引库
     * @param id
     */
    @Override
    public void deleteItem(Long id) {
        try {
            //1.构建删除文档请求对象
            DeleteRequest deleteRequest = new DeleteRequest(INDEX).id(id.toString());
            //2.执行删除
            highLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
